#include "Window.h"
#include "ImageBuffer.h"

namespace Graphics
{
	HANDLE Window::rHnd = 0;
	HANDLE Window::wHnd = 0;

	Window::Window(int width = 0, int height = 0)
	{
		this->_width = width;
		this->_height = height;
		this->_currentBuffer = 0;

		this->_buffers = new ImageBuffer[2];

		for(int i = 0; i < 2; i++)
			_buffers[i] = ImageBuffer(width, height);

		this->rHnd = GetStdHandle(STD_INPUT_HANDLE);
		this->wHnd = GetStdHandle(STD_OUTPUT_HANDLE);

		SetConsoleTitle(TEXT("Win32 Console Game"));

		SMALL_RECT windowSize = {0, 0, width-1, height-1};

		SetConsoleWindowInfo(wHnd, TRUE, &windowSize);

		COORD bufferSize = {width, height};

		SetConsoleScreenBufferSize(wHnd, bufferSize);
		
		CONSOLE_CURSOR_INFO info;
		info.bVisible = false;
		info.dwSize = 1;

		SetConsoleCursorInfo(wHnd, &info);
		SetConsoleCursorInfo(rHnd, &info);
	}

	Window::~Window()
	{ delete [] this->_buffers; }

	void Window::Present()
	{
		this->_renderingLocked = true;

		ImageBuffer* buffer = &this->_buffers[_currentBuffer];

		Pixel* data = buffer->getDataPtr();

		SMALL_RECT writeArea = {0, 0, _width-1, _height-1};
		COORD buffSize = {_width, _height};
		COORD charPos = {0, 0};

		WriteConsoleOutput(wHnd, data, buffSize, charPos, &writeArea);
		
		// Swap the buffers
		this->_currentBuffer = (this->_currentBuffer + 1) % 2;

		this->_renderingLocked = false;
	}
}